"""
created@2019/11/4
"""

from flask_restful import Resource, reqparse
from sqlalchemy import desc
from models.silo import Group
from utils.resp import Resp
from extensions import db
from log import logger
from daemon.task import update_total_count


class GroupListApi(Resource):

    def get(self):
        """获取群组列表接口"""

        groups = Group.query.filter(Group.parent_id == 0).order_by(desc(Group.created_at)).all()
        """
        SELECT silo.`groups`.id AS silo_groups_id, silo.`groups`.created_at AS silo_groups_created_at, silo.`groups`.updated_at AS silo_groups_updated_at, silo.`groups`.wx_app_id AS silo_groups_wx_app_id, silo.`groups`.parent_id AS silo_groups_parent_id, silo.`groups`.title AS silo_groups_title, silo.`groups`.description AS silo_groups_description, silo.`groups`.query_sql AS silo_groups_query_sql, silo.`groups`.deleted_at AS silo_groups_deleted_at, silo.`groups`.total_count AS silo_groups_total_count
        FROM silo.`groups`
        WHERE silo.`groups`.parent_id = %(parent_id_1)s 
        ORDER BY silo.`groups`.created_at DESC  {'parent_id_1': 0}  
        """
        data = []
        sql = """select group_concat(`groups`.wx_app_id), `groups`.parent_id
                    as parent_id 
                    from `groups`
                    join silo_wx_apps swa on `groups`.wx_app_id = swa.wx_app_id
                    where `groups`.parent_id != 0
                    group by `groups`.parent_id"""
        logger.info('\n获取子组wx_app_id列表的sql: \n{}'.format(sql))
        rows = db.session.execute(sql)
        
        wx_apps_id_dict = {}
        for row in rows:
            wx_apps_id_dict[row.values()[1]] = list(map(int, row.values()[0].split(",")))
        for group in groups:
            dicts = {
                "group_id": group.id,
                'wx_apps_id': wx_apps_id_dict.get(group.id) if wx_apps_id_dict.get(group.id) else [group.wx_app_id],
                'title': group.title,
                'description': group.description,
                'query_sql': group.query_sql,
                'total_count': group.total_count,
                'parent_id': group.parent_id
                }
            data.append(dicts)

        return Resp.ok(data=data)

    def post(self):
        """创建一个用户群组"""

        parser = reqparse.RequestParser()
        parser.add_argument('title', type=str, required=True)
        parser.add_argument('description', type=str, required=True)
        parser.add_argument('query_sql', type=str, required=True)
        parser.add_argument('wx_apps_id', type=list, location='json', required=True)
        args = parser.parse_args()
        if len(args["wx_apps_id"]) == 0:
            return Resp.bad_request(errmsg='wx_apps_id数组长度不能为0')

        # 公众号为一个的群组
        if len(args["wx_apps_id"]) == 1:
            wx_app_id = args["wx_apps_id"][0]
            total_count_sql = args["query_sql"].format(wx_app_id)
            
            group = Group(
                title=args['title'],
                description=args['description'],
                query_sql=total_count_sql,
                wx_app_id=args['wx_apps_id'][0],
                parent_id=0,
                total_count=0
            )
            db.session.add(group)
            db.session.flush()
            # update_total_count.delay(total_count_sql, group.id)   # todo:  异步任务
            logger.info('发送异步任务, 更新total_count')

            data = {
                "wx_apps_id": args["wx_apps_id"],
                "group_id": group.id,
                "title": args["title"],
                "description": args["description"],
                "query_sql": args['query_sql'],
                "total_count": 0,
            }

        else:
            # 对应多个公众号的群组
            # 创建父组
            group_parent = Group(
                title=args['title'],
                description=args['description'],
                wx_app_id=0,
                parent_id=0,
                total_count=0,
                query_sql=args['query_sql']
            )
            db.session.add(group_parent)
            """
            INSERT INTO silo.`groups` (created_at, updated_at, wx_app_id, parent_id, title, description, query_sql, deleted_at, total_count) VALUES (%(created_at)s, %(updated_at)s, %(wx_app_id)s, %(parent_id)s, %(title)s, %(description)s, %(query_sql)s, %(deleted_at)s, %(total_count)s)
            """
            db.session.flush()

            for i in args["wx_apps_id"]:
                query_sql = args['query_sql'].format(i)

                group_child = Group(
                    title=args['title'],
                    description=args['description'],
                    query_sql=query_sql,
                    wx_app_id=i,
                    parent_id=group_parent.id,
                    total_count=0
                    )
                db.session.add(group_child)
                db.session.flush()
                # update_total_count.delay(query_sql, group_child.id)  # todo: 异步任务 1

            data = {
                "wx_apps_id": args["wx_apps_id"],
                "group_id": group_parent.id,
                "title": args["title"],
                "description": args["description"],
                "query_sql": args['query_sql'],
                "total_count": 0,
            }
        db.session.commit()
        """
        SELECT silo.`groups`.id AS silo_groups_id, silo.`groups`.created_at AS silo_groups_created_at, silo.`groups`.updated_at AS silo_groups_updated_at, silo.`groups`.wx_app_id AS silo_groups_wx_app_id, silo.`groups`.parent_id AS silo_groups_parent_id, silo.`groups`.title AS silo_groups_title, silo.`groups`.description AS silo_groups_description, silo.`groups`.query_sql AS silo_groups_query_sql, silo.`groups`.deleted_at AS silo_groups_deleted_at, silo.`groups`.total_count AS silo_groups_total_count
        FROM silo.`groups`
        WHERE silo.`groups`.id = %(param_1)s
        """
        return Resp.ok(data=data)
